<template>
  <a-modal :visible="visible" title="新增预算" width="50%" :footer="null" @cancel="handleCancel" >
    <a-form-model
      ref="ruleForm"
      :rules="rules"
      :model="form"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 10 }"
      labelAlign="left"
    >
      <a-form-model-item label="新增金额" prop="budgetAmount" >
        <a-input
          v-model="form.budgetAmount"
          placeholder="请输入申报金额"
          :min="0.01"
          :precision="2"
          @input="(e) => (this.form.budgetAmount = $options.filters.amountCheck(e.target.value))"
          style="width: 90%;"/>
      </a-form-model-item>
      <a-form-model-item label="支付日期" prop="payTime" >
        <a-date-picker v-model="form.payTime" placeholder="年-月-日" :format="'YYYY-MM-DD'" :valueFormat="'YYYY-MM-DD'" style="width: 90%;" />
      </a-form-model-item>
      <a-form-model-item label="支付单号" prop="payNo" >
        <a-input
          v-model="form.payNo"
          placeholder="请输入支付单号"
        />
      </a-form-model-item>
      <a-form-model-item label="相关凭证" prop="proofUrl" >
        <div class="clearfix">
          <span>凭证仅可上传一张，支持格式：PNG/JPG</span>
          <a-upload
            action="/api/common/upload"
            list-type="picture-card"
            :file-list="fileList"
            :beforeUpload="beforeUpload"
            @preview="handlePreview"
            @change="handleChange"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </a-form-model-item>
      <a-button
        type="primary"
        @click="submit"
      >
        提交
      </a-button>
    </a-form-model>
  </a-modal>
</template>
<script>
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      form: {
        budgetAmount: '',
        payTime: '',
        payNo: '',
        proofUrl: ''
      },
      rules: {
        budgetAmount: [{ required: true, validator: this.moneyValidate, trigger: 'blur' }],
        payTime: [{ required: true, message: '请选择支付日期' }],
        payNo: [{ required: true, message: '请输入支付单号' }],
        proofUrl: [{ required: true, message: '请上传相关凭证', trigger: 'blur' }]
      },
      fileList: [],
      stopUpload: false,
      previewVisible: false,
      previewImage: ''
    }
  },
  watch: {
    visible (e) {
      if (!e) {
        this.form = this.$options.data().form
        this.fileList = []
        this.$refs.ruleForm.resetFields()
      }
    }
  },
  methods: {
    moneyValidate (rule, value, callback) {
      if (!value || +value <= 0) {
        callback(new Error('申报金额需大于0')) // eslint-disable-line
        return
      }
      callback()
    },
    submit () {
      this.$refs.ruleForm.validate(flag => {
        if (flag) {
          this.$emit('ok', this.form)
        }
      })
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange ({ file, fileList }) {
      if (this.stopUpload) {
        this.fileList = []
        return
      }
      this.fileList = fileList
      console.log('fileList', file, fileList)
      if (file.status === 'done') {
        if (file.response && file.response.data) {
          this.form.proofUrl = file.response.data
          console.log('success', this.fileList)
          if (this.fileList.length > 1) {
            this.fileList = fileList.slice(-1)
          }
        } else {
          this.fileList = []
          this.$message.error(file.response.detail || '上传失败')
        }
      }
    },
    // 校验图片格式是否符合要求
    beforeUpload (file) {
      const typeVal = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png'
      if (!typeVal) {
        this.$message.error('图片格式仅支持“jpg/jpeg/png”')
        this.stopUpload = true
      } else {
        this.stopUpload = false
      }
      return typeVal
    },
    handleCancel () {
      this.$emit('handleCancel')
    }
  }
}
</script>
<style lang="less" scoped>

</style>
